package com.doudou.oauth.handler;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 傻男人
 * @date 2020-05-08 22:02
 * @describe 退出登录成功的处理逻辑
 */
public class SuccessLogoutHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    @Setter
    @Getter
    ConsumerTokenServices consumerTokenServices;

    String redirectUrl = "redirect_url";

    public SuccessLogoutHandler() {
        this(null);
    }

    public SuccessLogoutHandler(String redirectUrl) {
        this(redirectUrl, null);
    }

    public SuccessLogoutHandler(String redirectUrl, ConsumerTokenServices tokenServices) {
        if (!StringUtils.isEmpty(redirectUrl)) {
            this.redirectUrl = redirectUrl;
        }
        this.consumerTokenServices = tokenServices;
        setTargetUrlParameter(this.redirectUrl);
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getParameter("token");
        super.handle(request, response, authentication);
        if (!StringUtils.isEmpty(token)) {
            consumerTokenServices.revokeToken(token);
        }
    }

    protected String determineTargetUrl(HttpServletRequest request,
                                        HttpServletResponse response) {
        String target = super.determineTargetUrl(request, response);
        StringBuilder sb = new StringBuilder();
        sb.append(target);
        if (!target.contains("?")) {
            sb.append("?");
        } else {
            sb.append("&");
        }
        sb.append("remote_logout=true");
        return sb.toString();
    }
}
